var generator = require('../generator/generator');
var employee = require('../model/employee');
var file = require('../model/file');
var record = require('../model/record');
var log = require('../model/log');
var performance = require('../model/performance');
var users = require('../model/user');
var role = require('../model/role');
var organization = require('../model/organization');

/*
	查询所有员工
*/
exports.selectEmp = function(req, res, connection) {
	employee.selectEmp(connection, function(rows) {
		if (rows != null && rows.length != 0) {
			res.send(rows);
		} else {
			res.send("none");
		}
	});
};
/*
	查询有审核权限的员工
*/
exports.selEmpByRole = function(req, res, connection) {
	employee.selEmpAss(connection, function(rows) {
		if (rows != null && rows.length != 0) {
			res.send(rows);
		} else {
			res.send("none");
		}
	})
};
/*
  根据员工姓名查询有审核权限的员工
*/
exports.selEmpAssByName = function(req, res, connection) {
	var empName = req.query.empName;
	console.log("empName",empName);
	employee.selEmpAssByName(connection,empName, function(rows) {
		console.log("test---------rows", rows);
		if (rows != null && rows.length != 0) {
			res.send(rows);
		} else {
			res.send("none");
		}
	})
};

/*
	增加员工信息
*/
exports.addEmp = function(req, res, connection) {
	var data = req.body;

	var sendData = {
		name: data.name,
		gender: data.gender,
		idNumber: data.idNumber,
		address: data.address,
		email: data.email,

		phone: data.phone,
		education: data.education,
		registeredResidence: data.registeredResidence,
		workPlace: data.workPlace,
		emContactPerson: data.emContactPerson,

		emContactPhone: data.emContactPhone,
		graduInstitutions: data.graduInstitutions,
		birthDate: data.birthDate,
		residenceType: data.residenceType,
		graduateTime: data.graduateTime,

		jobNumber: data.jobNumber,
		contractNum: data.contractNum,
		job: data.job,
		jobCategory: data.jobCategory,
		departmentId: data.departmentId,

		state: data.state,
		entryTime: data.entryTime,
		departureTime: data.departureTime,
		dateOfCStart: data.dateOfCStart,
		dateOfCEnd: data.dateOfCEnd,

		dateOfRenewalStart: data.dateOfRenewalStart,
		dateOfRenewalEnd: data.dateOfRenewalEnd,
		bandLevel: data.bandLevel,
		currentSalary: data.currentSalary * 1,
		salaryLevel: data.salaryLevel,

		bankCardNum: data.bankCardNum,
		housingFundCard: data.housingFundCard,
		smInsuranceCard: data.smInsuranceCard,
		ifProbation: data.ifProbation,
		probationaryPeriod: data.probationaryPeriod,

		confirmationDate: data.confirmationDate,
		lastDateOfPromotion: data.lastDateOfPromotion,
		lastDateOfExamination: data.lastDateOfExamination,
		lastDateOfRise: data.lastDateOfRise
	};
	var files = data.file;
	var user = req.user;
	employee.addEmp(connection, sendData, function(rows) {
		if (rows != null && rows.length != 0) {
			// console.log('rows:::', rows.insertId);
			if (files != null || files != undefined) {
				file.move(connection, files, rows.insertId, user.employeeId, function(data) {
					// console.log('data:', data);
				});
			}
			var id = rows.insertId;
			
			// role.selectRole(connection,function(data){
			// 	var role = [];
			// 	for(var i = 0; i < data.length; i ++){
			// 		if(data[i].roleName == '被考核人'){
			// 			role.push(data[i].id);
			// 		}
			// 	}
			// 	var uName = sendData.email.split('@')[0];
			// 	console.log('uName::', uName);
			// 	var userData = {
			// 		userName: uName,
			// 		password: uName,
			// 		employeeId: id,
			// 		role: role
			// 	}
			// 	users.add(connection, userData, function(result){
			// 		console.log(result);
			// 	});
			// });
			employee.findById(connection, id, function(data) {
				// console.log('datdatadat:', data[0]);
				var content = JSON.stringify(data[0]);
				console.log('content', content);
				var logData = {
					itemId: id,
					updatePersonId: user.employeeId,
					content: content,
					type: 0,
					operation: '增加'
				};
				log.addLog(connection, logData, function(log) {
					console.log('log', log);
					if (log != null && log != undefined)
						console.log('add log success');
				});
			});

			res.send(rows);
		} else {
			res.send("fail");
			console.info('error');
		}

	})
};

/*
	修改员工信息
*/
exports.updateEmp = function(req, res, connection) {
	var data = req.body;
	var empId = req.params['id'];
	var jobBefore = data.jobBefore;
	var salaryBefore = data.salaryBefore;
	var deptBefore = data.departmentBefore;
	var str = deptBefore.split('/')[0];
	var deptNow = data.departmentNow;
	var time = data.time;

	var empData = {
		id: empId,
		name: data.name,
		gender: data.gender,
		idNumber: data.idNumber,
		address: data.address,
		email: data.email,

		phone: data.phone,
		education: data.education,
		registeredResidence: data.registeredResidence,
		workPlace: data.workPlace,
		emContactPerson: data.emContactPerson,

		emContactPhone: data.emContactPhone,
		graduInstitutions: data.graduInstitutions,
		birthDate: data.birthDate,
		residenceType: data.residenceType,
		graduateTime: data.graduateTime,

		jobNumber: data.jobNumber,
		contractNum: data.contractNum,
		job: data.job,
		jobCategory: data.jobCategory,
		departmentId: data.departmentId,

		state: data.state,
		entryTime: data.entryTime,
		departureTime: data.departureTime,
		dateOfCStart: data.dateOfCStart,
		dateOfCEnd: data.dateOfCEnd,

		dateOfRenewalStart: data.dateOfRenewalStart,
		dateOfRenewalEnd: data.dateOfRenewalEnd,
		bandLevel: data.bandLevel,
		currentSalary: data.currentSalary * 1,
		salaryLevel: data.salaryLevel,

		bankCardNum: data.bankCardNum,
		housingFundCard: data.housingFundCard,
		smInsuranceCard: data.smInsuranceCard,
		ifProbation: data.ifProbation,
		probationaryPeriod: data.probationaryPeriod,

		confirmationDate: data.confirmationDate,
		lastDateOfPromotion: data.lastDateOfPromotion,
		lastDateOfExamination: data.lastDateOfExamination,
		lastDateOfRise: data.lastDateOfRise
	};
	var upgradeData = {};
	var salaryData = {};
	var dataArray = [];
	if(data.recordItems!=undefined){
		dataArray=data.recordItems;
	}
	// if (jobBefore != data.job) {
	// 	upgradeData = {
	// 		recordName: '升职记录',
	// 		type: 'upgrade',
	// 		content: '职位由 ' + jobBefore + ' 调整为 ' + data.job,
	// 		employeeId: empId,
	// 		recordDate: new Date()
	// 	};
	// 	dataArray.push(upgradeData);
	// }
	// if (salaryBefore != data.currentSalary) {
	// 	salaryData = {
	// 		recordName: '加薪记录',
	// 		type: 'addSalary',
	// 		content: '薪水由 ' + salaryBefore + ' 调整为 ' + data.currentSalary,
	// 		employeeId: empId,
	// 		recordDate: new Date()
	// 	};
	// 	dataArray.push(salaryData);
	// }
	// if (deptNow.split('/')[0] == str && deptNow != deptBefore) {
	// 	deptData = {
	// 		recordName: '部门调整',
	// 		type: 'departChange',
	// 		content: '部门由 ' + deptBefore + ' 调整为 ' + deptNow,
	// 		employeeId: empId,
	// 		recordDate: new Date()
	// 		// flag: true
	// 	};
	// 	dataArray.push(deptData);
	// }
	var files = data.file;
	var user = req.user;
	employee.updateEmp(connection, empData, function(rows) {
		if (dataArray.length != 0) {
			console.log('dataArray:', dataArray);
			for (var i = 0; i < dataArray.length; i++) {
				record.addRecord(connection, dataArray[i], function(info) {
					console.log('info:', info);
				});
				//如果变更了员工部门，修改当月该员工绩效表中的部门
				// if(dataArray[i].flag) {
				// 	performance.updEmpPerf(connection, dataArray[i].employeeId, time, dataArray[i].deptNow);
				// }
			}
		}
		if (rows != null && rows.length != 0) {
			if (files != null || files != undefined) {
				file.move(connection, files, empId, user.employeeId, function(data) {
					console.log('data:', data);
				});
			}
			//console.log('idididididid',empData.id);
			employee.findById(connection, empData.id, function(data) {
				//console.log('datdatadat:', data[0]);
				var content = JSON.stringify(data[0]);
				//console.log('content', content);
				var logData = {
					itemId: empData.id,
					updatePersonId: user.employeeId,
					content: content,
					type: 0,
					operation: '修改'
				};
				log.addLog(connection, logData, function(log) {
					//console.log('log', log);
					if (log != null && log != undefined)
						console.log('add log success');
				});
			});
			res.send(data);
		} else {
			res.send("fail");
		}
	});
};

/*
	删除员工信息
*/
exports.delEmp = function(req, res, connection) {
	var id = req.params['id'];
	var user = req.user;
	employee.deleteEmp(connection, id, function(rows) {
		// console.log('rowrowded:', rows);
		var content = JSON.stringify(rows);
		var logData = {
			itemId: id,
			updatePersonId: user.employeeId,
			content: content,
			type: 0,
			operation: '删除'
		};
		log.addLog(connection, logData, function(log) {
			// console.log('log', log);
			if (log != null && log != undefined)
				console.log('add log success');
		});
		res.send("success");
		// res.send(generator.generate('staff', {
		// 	username: req.user.userName,
		// 	name: req.user.name
		// }));
	});
};

exports.selectOneEmp = function(req, res, connection) {
	var id = req.params['id'];
	employee.findById(connection, id, function(rows) {
		res.send(rows);
	});
};

exports.getEmpByName = function(req, res, connection) {
	// console.log("11111111111111111111");
	var empName = req.query.empName;
	employee.selEmpByName(connection, empName, function(rows) {
		// console.log("emp----", rows);
		res.send(rows);
	});
};

exports.searchByKey = function(req, res, connection) {
	var key = req.query.keyword;
	var advancedKey = req.query.advancedKey;
	var cpage = req.query.cpage;
	var pageSize = req.query.pageSize;
	var begin = pageSize * (cpage - 1);
	var end = pageSize * cpage - 1;
	if(advancedKey == ""){
		employee.searchByKey(connection, key, function(rows) {
			var data = [];
			var k = 0;
			if(cpage == -1) {
				begin = pageSize * (Math.ceil(rows.length / pageSize) - 1);
				end = rows.length;
			}
			
			for (var i = begin; i < end + 1; i++) {
				if (i < rows.length) {
					data[k] = rows[i];
					k++;
				}
			}
			var sendData = {
				data: data,
				count: rows.length
			}
			res.send(sendData);
		});
	}else{// 高级搜索
		var advancedKeyword = JSON.parse(advancedKey);
		if (advancedKeyword.key == 1) {
			employee.selEmpByOrg(connection, advancedKeyword.value,key, function(rows) {
				var data = [];
				var k = 0;
				for (var i = begin; i < end + 1; i++) {
					if (i < rows.length) {
						data[k] = rows[i];
						k++;
					}
				}
				var sendData = {
					data: data,
					count: rows.length
				}
				res.send(sendData);
			});
		}else{
			employee.selEmpByEntryOrDeparture(connection, advancedKeyword, function(rows) {
				var data = [];
				var k = 0;
				for (var i = begin; i < end + 1; i++) {
					if (i < rows.length) {
						data[k] = rows[i];
						k++;
					}
				}
				var sendData = {
					data: data,
					count: rows.length
				}
				res.send(sendData);
			});
		}
	}
};

exports.delListEmp = function(req, res, connection) {
	var idData = req.body;
	console.log('idData', idData);
	var ids = idData.ids;
	var array = [];
	for (var i = 0; i < ids.length; i++) {
		employee.deleteEmp(connection, ids[i], function(rows) {
			array.push(rows);
		});
	}
	res.send(array);
};

exports.selEmpByUser = function(req, res, connection) {
	var user = req.user;
	// console.log("selEmpByUser--user.employeeId:", user.employeeId);
	employee.selEmpByUser(connection, user.employeeId, function(rows) {
		if (rows != null && rows.length != 0) {
			res.send(rows[0]);
		} else {
			res.send([]);
		}

	});
};

exports.selEmpByOrg = function(req, res, connection) {
	var orgId = req.query.orgId;
	var keyword = req.query.keyword;
	var cpage = req.query.cpage;
	var pageSize = req.query.pageSize;
	var begin = pageSize * (cpage - 1);
	var end = pageSize * cpage - 1;
	organization.findById(connection, orgId, function(results) {
		if(results != null && results != undefined) {
			if(results[0].orgAddress == 'D') {
				employee.selEmpByOrg(connection, orgId, keyword, function(rows) {
					var data = [];
					var k = 0;
					for(var i = begin; i < end + 1; i++) {
						if(i < rows.length) {
							data[k] = rows[i];
							k++;
						}
					}
					var sendData = {
						data: data,
						count: rows.length
					};
					res.send(sendData);
				});
			}else{
				var ids = [];
				var idList = [];
				ids.push(orgId);
				idList.push(orgId);
				exports.selChildrenByIds(connection, ids, idList, function(idData) {
					
					employee.selEmpByOrgIds(connection, idData, keyword, function(rows) {
						// console.log("lijuanxia---", rows.length);
						var data = [];
						var k = 0;
						for(var i = begin; i < end + 1; i++) {
							if(i < rows.length) {
								data[k] = rows[i];
								k++;
							}
						}
						var sendData = {
							data: data,
							count: rows.length
						};
						res.send(sendData);
					});
				});
				
			}
		}
	});
	

};
//根据机构id数字查询子机构
exports.selChildrenByIds = function(connection, ids, idList, callback) {
	organization.findOrgByIds(connection, ids, function(rows) {
		if(rows != null && rows.length != 0) {
			var ids_new = [];
			for(var i = 0; i < rows.length; i++) {
				idList.push(rows[i].id);
				ids_new.push(rows[i].id);
			}
			exports.selChildrenByIds(connection, ids_new, idList, function(data) {
				callback(data);
			});
		}else{
			callback(idList);
		}
	});
};